//
//  ChatViewController+Helper.swift
//  EyeVisionForDoctors
//
//  Created by PMC on 2020/2/17.
//  Copyright © 2020 tao Tao. All rights reserved.
//

import UIKit
import Photos

extension ChatViewController {
    func sendImageMsg(_ model: UploadImgModel) {
        DispatchQueue.main.async { [weak self] in
            guard let strongSelf = self else { return }
            let imgVm = UploadImgViewModel(model: model)
            guard let vm = strongSelf.viewModel, let detailVm = strongSelf.detailVM else { return }
            let msgModel = ChatMsgModel(
                sendTime: Date().toString(format: "HH:mm"),
                fromType: 0,
                messageId: "",
                content: imgVm.thumbnailPath,
                messageType: ChatMsgType.image.rawValue,
                src: imgVm.originalPath,
                chatType: 2,
                cmd: 11,
                createTime: Date.milliseconds,
                diagnoseId: detailVm.diagnoseId,
                docId: detailVm.chatReceiveId,
                docName: detailVm.chatReceiveName,
                from: detailVm.chatSendId,
                msgType: ChatMsgType.image.rawValue,
                roleType: 0,
                testType: 0,
                to: detailVm.chatReceiveId,
                clientId: Date.milliStamp + String.randomOfFive,
                isSending: true
            )
            vm.insert(msgModel: msgModel)
            let insertIndexPath = IndexPath(row: vm.numberOfRows - 1,
                                            section: strongSelf.tableView.numberOfSections - 1)
            strongSelf.tableView.insertRowsAtBottom([insertIndexPath])
            
            self?.waitSendMsgs.append(msgModel)
            
            WebSocketManager.shared().sendMessage(msgModel)
        }
    }
    
    func sendTextMsg() {
        DispatchQueue.main.async { [weak self] in
            guard let strongSelf = self else { return }
            let textView = strongSelf.chatBarView.inputTextView
            guard textView.text.count < 1000 else {
                HUDTool.show(message: "超出字数限制")
                return
            }
             
            if textView.text.trimmingCharacters(in: .whitespaces).count == 0 {
                HUDTool.show(message: "不能发送空白信息")
                return
            }
            
            guard let vm = strongSelf.viewModel, let detailVm = strongSelf.detailVM else { return }
            let msgModel = ChatMsgModel(
                sendTime: Date().toString(format: "HH:mm"),
                fromType: 0,
                messageId: "",
                content: textView.text,
                messageType: ChatMsgType.text.rawValue,
                chatType: 2,
                cmd: 11,
                createTime: Date.milliseconds,
                diagnoseId: detailVm.diagnoseId,
                docId: detailVm.chatReceiveId,
                docName: detailVm.chatReceiveName,
                from: detailVm.chatSendId,
                msgType: ChatMsgType.text.rawValue,
                roleType: 0,
                testType: 0,
                to: detailVm.chatReceiveId,
                clientId: Date.milliStamp + String.randomOfFive,
                isSending: true
            )
            vm.insert(msgModel: msgModel)
            let insertIndexPath = IndexPath(row: vm.numberOfRows - 1,
                                            section: strongSelf.tableView.numberOfSections - 1)
            strongSelf.tableView.insertRowsAtBottom([insertIndexPath])
            
            self?.waitSendMsgs.append(msgModel)
            // 发送消息
            WebSocketManager.shared().sendMessage(msgModel)
            
            textView.text = ""
            strongSelf.textViewDidChange(textView)
        }
    }
    
    func sendAudioMsg(_ model: UploadAudioModel) {
        DispatchQueue.main.async { [weak self] in
            guard let strongSelf = self else { return }
            guard let vm = strongSelf.viewModel, let detailVm = strongSelf.detailVM else { return }
            let msgModel = ChatMsgModel(
                sendTime: Date().toString(format: "HH:mm"),
                fromType: 0,
                messageId: "",
                content: model.shareUrl,
                messageType: ChatMsgType.voice.rawValue,
                time: model.time,
                chatType: 2,
                cmd: 11,
                createTime: Date.milliseconds,
                diagnoseId: "\(detailVm.diagnoseId)",
                docId: "\(detailVm.chatReceiveId)",
                docName: "\(detailVm.chatReceiveName)",
                from: detailVm.chatSendId,
                msgType: ChatMsgType.voice.rawValue,
                roleType: 0,
                testType: 0,
                to: "\(detailVm.chatReceiveId)",
                clientId: Date.milliStamp + String.randomOfFive,
                isSending: true
            )
            vm.insert(msgModel: msgModel)
            let insertIndexPath = IndexPath(row: vm.numberOfRows - 1,
                                            section: strongSelf.tableView.numberOfSections - 1)
            strongSelf.tableView.insertRowsAtBottom([insertIndexPath])
            
            self?.waitSendMsgs.append(msgModel)
            
            WebSocketManager.shared().sendMessage(msgModel)
        }
    }
    
    func controlExpandableInputView(showExpandable: Bool) {
        let textView = chatBarView.inputTextView
        let currentTextHeight = chatBarView.inputTextViewCurrentHeight
        UIView.animate(withDuration: kKeyboardChangeFrameTime, animations: { () -> Void in
            let textHeight = showExpandable ? currentTextHeight : kChatBarViewOriginalHeight
            self.chatBarView.snp.updateConstraints { (make) in
                make.height.equalTo(textHeight)
            }
            self.view.layoutIfNeeded()
            self.tableView.scrollBottomToLastRow()
            textView.contentOffset = .zero
        })
    }
    
    func insertUnstartCell(_ detailVm: AdvisoryDetailViewModel) {
        if let vm = viewModel?.msgModels.first,
            vm.messageType == ChatMsgType.unstart.rawValue { return }
        
        let msgModel = ChatMsgModel(
            sendTime: detailVm.createTime,
            messageType: ChatMsgType.unstart.rawValue
        )
        viewModel?.msgModels = [msgModel]
    }
    
    func insertStartCell(_ detailVm: AdvisoryDetailViewModel) {
        if let vm = viewModel?.msgModels.first,
            vm.messageType == ChatMsgType.start.rawValue { return }
        
        let msgModel = ChatMsgModel(
            sendTime: detailVm.acceptTime,
            messageType: ChatMsgType.start.rawValue
        )
        viewModel?.insert(msgModel: msgModel, isBottom: false)
    }
    
    func insertEndCell(_ detailVm: AdvisoryDetailViewModel) {
        if let vm = viewModel?.msgModels.last,
            vm.messageType == ChatMsgType.end.rawValue { return }
        
        let msgModel = ChatMsgModel(
            sendTime: detailVm.endTime,
            messageType: ChatMsgType.end.rawValue
        )
        viewModel?.insert(msgModel: msgModel)
    }
}

// MARK: - 相册、相机
extension ChatViewController {
    func showBottomAlert() {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        let cancel = UIAlertAction(title:"取消", style: .cancel, handler: nil)
        let takingPictures = UIAlertAction(title:"拍照", style: .default) {
            action in
            self.cameraTapped()
            
        }
        let localPhoto = UIAlertAction(title:"从手机相册选择", style: .default) {
            action in
            self.openPhoto()
            
        }
        alert.addAction(cancel)
        alert.addAction(takingPictures)
        alert.addAction(localPhoto)
        present(alert, animated:true, completion:nil)
    }
    
    /// 选择拍照
    func cameraTapped() {
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        switch authStatus {
        case .notDetermined:
            checkCameraPermission()
        case .restricted, .denied:
            AlertTool.showAlert(self, title: "无法访问您的相机", message: "请到设置 -> 隐私 -> 相机，打开访问权限", sureTitle: "知道了")
        case .authorized:
            openCamera()
        default: break
        }
    }
    
    func openCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
//            cameraPicker.allowsEditing = true
            cameraPicker.sourceType = .camera
            cameraPicker.modalPresentationStyle = .fullScreen
            present(cameraPicker, animated: true, completion: nil)
        } else {
            AlertTool.showAlert(self, title: "无法访问您的相机", message: "请到设置 -> 隐私 -> 相机，打开访问权限", sureTitle: "知道了")
        }
    }
    
    func checkCameraPermission () {
        AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: {granted in
            if !granted {
                AlertTool.showAlert(self,
                                    title: "无法访问您的相机",
                                    message: "请到设置 -> 隐私 -> 相机，打开访问权限",
                                    sureTitle: "知道了")
            }
        })
    }
    
    func openPhoto() {
        let photoPicker =  UIImagePickerController()
        photoPicker.delegate = self
//        photoPicker.allowsEditing = true
        photoPicker.sourceType = .photoLibrary
        photoPicker.modalPresentationStyle = .fullScreen
        present(photoPicker, animated: true, completion: nil)
    }
}
